﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Xml.Linq;

namespace SoftWareBoot
{
    /// <summary>
    /// Window_AutoUpdate.xaml 的交互逻辑
    /// </summary>
    public partial class Window_AutoUpdate : Window
    {
        /// <summary>
        /// 升级项目名称
        /// </summary>
        public string ProjectName
        {
            private get;

            set;
        }
        /// <summary>
        /// 服务对象
        /// </summary>
        private AutoUpdateService.AutoUpdateClient client = null;

        /// <summary>
        /// 服务器版本,服务器时间,本地版本,本地时间
        /// </summary>
        private string newVersion, newVerDate, localVersion, localVerDate;

        /// <summary>
        /// 更新页面
        /// </summary>
        private Page_Down pageDown = null;

        /// <summary>
        /// 设置参数
        /// </summary>
        /// <param name="Client">服务对象</param>
        /// <param name="NewVersion">升级版本</param>
        /// <param name="NewVerDate">时间时间</param>
        /// <param name="LocalVersion">本地版本</param>
        /// <param name="LocalVerDate">本地时间</param>
        public void SetData(AutoUpdateService.AutoUpdateClient Client, string NewVersion, string NewVerDate, string LocalVersion, string LocalVerDate)
        {
            client = Client;
            newVerDate = NewVerDate;
            newVersion = NewVersion;
            localVerDate = LocalVerDate;
            localVersion = LocalVersion;
            Txt_AutoName.Text = string.Format("{0} 程序集文件自动升级系统", ProjectName);

            Page_One page1 = new Page_One();

            page1.SetInfo(newVersion, newVerDate, localVersion, localVerDate);

            frame_Page.Content = page1;
        }

        /// <summary>
        /// 启动的程序完整路径
        /// </summary>
        public string StartProgramPath
        {
            get;

            private set;
        }

        public Window_AutoUpdate()
        {
            InitializeComponent();

            XDocument xDoc = new XDocument();

            string path = string.Format(@"{0}\{1}", System.Environment.CurrentDirectory, "UIConfig.xml");

            if (System.IO.File.Exists(path))
            {
                try
                {
                    xDoc = XDocument.Load(path);

                    if (xDoc.Element("Config").Descendants("Item").Where((xe) => xe.Attribute("Name").Value == "Company").Count() == 0)
                    {
                        xDoc.Element("Config").Add(new XElement("Item", new XAttribute("Name", "Company"), new XAttribute("Value", "请在UICONFIG.XML中填写你的公司名称")));
                        xDoc.Save(path);
                    }
                }
                catch
                {
                    xDoc = new XDocument();

                    xDoc.Add(new XElement("Config", new XElement("Item", new XAttribute("Name", "Company"), new XAttribute("Value", "请在UICONFIG.XML中填写你的公司名称"))));
                    xDoc.Save(path);
                }
            }
            else
            {
                xDoc.Add(new XElement("Config", new XElement("Item", new XAttribute("Name", "Company"), new XAttribute("Value", "请在UICONFIG.XML中填写你的公司名称"))));
                xDoc.Save(path);
            }

            Txt_Company.Text = (from xe in xDoc.Element("Config").Descendants("Item")
                                where xe.Attribute("Name").Value == "Company"
                                select xe.Attribute("Value").Value).First();

            Txt_Ver.Text += App.ResourceAssembly.GetName(false).Version;

        }


        /// <summary>
        /// 下一步按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Next_Click(object sender, RoutedEventArgs e)
        {

            Btn_Next.Visibility = System.Windows.Visibility.Collapsed;

            pageDown = new Page_Down(client, ProjectName);

            pageDown.Listloaded += pageDown_Listloaded;

            pageDown.FileDownOver += pageDown_FileDownOver;
            frame_Page.Content = pageDown;


        }

        /// <summary>
        /// 重试按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Retry_Click(object sender, RoutedEventArgs e)
        {
            Btn_Retry.Visibility = System.Windows.Visibility.Collapsed;
            Btn_Over.Visibility = System.Windows.Visibility.Collapsed;

            Btn_Update.Visibility = System.Windows.Visibility.Visible;

            pageDown.ReLoad();

            frame_Page.Content = pageDown;
        }

        /// <summary>
        /// 更新按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_UpDate_Click(object sender, RoutedEventArgs e)
        {
            Btn_Close.IsEnabled = false;
            Btn_Update.Visibility = System.Windows.Visibility.Collapsed;

            Page_Down pagedown = frame_Page.Content as Page_Down;

            if (pagedown == null)
            {
                MessageBox.Show("系统文件加载出错...", "错误提示", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            try
            {
                pagedown.UpdateFile();
            }
            catch (Exception ex)
            {
                pageDown_FileDownOver(ex.Message, null);
            }
        }


        /// <summary>
        /// 下载页下载完成事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pageDown_FileDownOver(object sender, EventArgs e)
        {
            Btn_Over.Visibility = System.Windows.Visibility.Visible;      //文件下载完成后完成按钮设置为可用
            Btn_Close.IsEnabled = true;                                 //文件下载完成后关闭按钮设置为可用

            string errstring = "";

            Page_Down page = sender as Page_Down;

            errstring = page == null ? errstring = sender.ToString() : page.ErrString;

            StartProgramPath = page.StartProgram;           //从Page_Down页面获取启动程序路径

            if (errstring == "")
            {
                try
                {
                    string programPath = string.Format(@"{0}\Bin", System.Environment.CurrentDirectory);

                    string tmpProgramPath = string.Format(@"{0}\Temp", System.Environment.CurrentDirectory);

                    if (System.IO.Directory.Exists(tmpProgramPath))
                    {
                        CopyUpdateFile(tmpProgramPath, programPath);

                        System.IO.Directory.Delete(tmpProgramPath, true);
                    }
                }
                catch (Exception ex)
                {
                    errstring = ex.Message;
                }
            }
            if (errstring != "")
            {
                Btn_Retry.Visibility = System.Windows.Visibility.Visible;
            }
            frame_Page.Content = new Page_Result(errstring);
        }

        /// <summary>
        /// 将升级下载文件从TEMP文件夹移动到Bin文件夹
        /// </summary>
        private static void CopyUpdateFile(string SourceDir, string DestDir)
        {


            if (!System.IO.Directory.Exists(DestDir)) System.IO.Directory.CreateDirectory(DestDir);

            if (!System.IO.Directory.Exists(SourceDir)) return;


            foreach (System.IO.FileSystemInfo f in (new System.IO.DirectoryInfo(SourceDir)).GetFileSystemInfos())
            {
                if (f is System.IO.FileInfo)
                {
                    ((System.IO.FileInfo)f).CopyTo(string.Format(@"{0}\{1}", DestDir, f.Name), true);
                }
                else if (f is System.IO.DirectoryInfo)
                {
                    CopyUpdateFile(f.FullName, string.Format(@"{0}\{1}", DestDir, f.Name));
                }
            }

        }

        /// <summary>
        /// 下载页列表加载完成返回消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pageDown_Listloaded(object sender, EventArgs e)
        {
            Btn_Update.Visibility = System.Windows.Visibility.Visible;          //下载列表加载完成后，显示更新按钮
        }

        /// <summary>
        /// 关闭按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Close_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        /// <summary>
        /// 操作结束按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Over_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        /// <summary>
        /// 重写正在关闭窗体事件
        /// </summary>
        /// <param name="e"></param>
        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            if (!Btn_Close.IsEnabled) e.Cancel = true;

            base.OnClosing(e);
        }




    }
}
